package com.party.web.biz.photo;

import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.commune.MomentType;
import com.party.core.model.file.ImgResource;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.photo.PhotosImgInfo;
import com.party.core.model.photo.PhotosImgTag;
import com.party.core.model.photo.PhotosTag;
import com.party.core.service.file.IImgResourceService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.photo.IPhotosImgInfoService;
import com.party.core.service.photo.IPhotosImgTagService;
import com.party.core.service.photo.IPhotosTagService;
import com.party.core.service.photo.biz.PhotosCountBizService;
import com.party.web.biz.member.CMomentBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.output.member.CMomentSave;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description: 相册分类
 * @Author: yangshoukun
 * @Date: 2018/5/30 14:23
 */
@Service
public class AlbumBizService {
    private static Logger logger = LoggerFactory.getLogger(AlbumBizService.class);

    @Autowired
    private IPhotosTagService photosTagService;

    @Autowired
    private IPhotosImgTagService photoAlbumPicService;

    @Autowired
    private IPhotosImgInfoService photosImgInfoService;

    @Autowired
    private IPhotoProjectService photoProjectService;

    @Autowired
    private PhotosCountBizService photosCountBizService;

    @Autowired
    private IImgResourceService imgResourceService;
    @Autowired
    private CMomentBizService momentBizService;

    /**
     * 列表
     * @param map
     * @param photosTag
     * @param page
     * @return
     */
    public List<PhotosTag> list(Map<String, Object> map, PhotosTag photosTag, Page page) {
        return photosTagService.webList(map, photosTag, page);
    }

    /**
     * 创建相册项目的时候, 初始化相册分类(自动添加: 时间线, 热门, 精选 三个分类)
     * @param photosId
     */
    @Transactional
    public void initTags(String photosId) {
        if (StringUtils.isEmpty(photosId)) {
            throw new BusinessException("photosId不能为空");
        }
        insertSystemTag(PhotosTag.ALBUM_CHOICENESS, photosId);
        insertSystemTag(PhotosTag.ALBUM_HOT, photosId);
        insertSystemTag(PhotosTag.ALBUM_TIME_LINE, photosId);
    }

    private void insertSystemTag(String name, String photosId) {
        PhotosTag photosTag = new PhotosTag();
        photosTag.setName(name);
        photosTag.setPhotosId(photosId);
        photosTag.setType(PhotosTag.TYPE_SYSTEM);

        List<PhotosTag> list = photosTagService.list(photosTag);
        if (CollectionUtils.isEmpty(list)) {
            MemberGroup member = RealmUtils.getCurrentUser();
            photosTag.setImgNum(0);
            photosTag.setCreateBy(member.getId());
            photosTag.setUpdateBy(member.getId());

            photosTagService.insert(photosTag);
        }
    }

    /**
     * 保存
     * @param photosTag
     */
    public void save(PhotosTag photosTag) {
        if (StringUtils.isEmpty(photosTag.getName())) {
            throw new BusinessException("分类名称不能为空");
        }

        PhotosTag param = new PhotosTag();
        param.setName(photosTag.getName());
        param.setPhotosId(photosTag.getPhotosId());

        PhotosTag dbTag = photosTagService.findByName(param);
        if (dbTag != null) {
            throw new BusinessException("该分类名称已经存在");
        }

        MemberGroup member = RealmUtils.getCurrentUser();
        if (StringUtils.isEmpty(photosTag.getId())) {
            photosTag.setImgNum(0);
            photosTag.setType(PhotosTag.TYPE_CUSTOM);
            photosTag.setCreateBy(member.getId());
            photosTag.setUpdateBy(member.getId());
            photosTagService.insert(photosTag);
        } else {
            PhotosTag db = photosTagService.get(photosTag.getId());
            db.setName(photosTag.getName());
            db.setUpdateBy(member.getId());
            db.setUpdateDate(new Date());
            photosTagService.update(db);
        }
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    public void delete(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("分类id不能为空");
        }
        PhotosTag photosTag = photosTagService.get(id);
        if (PhotosTag.TYPE_SYSTEM.equals(photosTag.getType())) {
            throw new BusinessException("不能删除系统的相册");
        }
        PhotosImgTag param = new PhotosImgTag();
        param.setTagId(id);
        List<PhotosImgTag> list = photoAlbumPicService.list(param);

        list.forEach(relation -> {
            // 查看与删除类型关联的照片是否有其他的类型关联, 没有就删除照片
            /*PhotosImgTag param2 = new PhotosImgTag();
            param2.setImgId(relation.getPicId());
            List<PhotosImgTag> list2 = photoAlbumPicService.list(param2);
            if (CollectionUtils.isEmpty(list2)) {
                photosImgInfoService.delete(relation.getPicId());
            }*/

            // 删除相册照片关系
            photoAlbumPicService.delete(relation.getId());
        });
        // 删除相册
        photosTagService.delete(id);
    }

    /**
     * 添加照片
     * @param projectId
     * @param albumId
     */
    @Transactional
    public void addPic(String projectId, String albumId, String urls, String imgResourceIds) {
        if (StringUtils.isEmpty(projectId)) {
            throw new BusinessException("项目id不能为空");
        }
        if (StringUtils.isEmpty(urls)) {
            throw new BusinessException("照片路劲不能为空");
        }
        String[] urlArray = urls.trim().split(",");
        String[] imgIdArray = imgResourceIds.split(",");

        boolean hasAlbum;
        if (StringUtils.isEmpty(albumId)) {
            hasAlbum = false;
        } else {
            PhotosTag photosTag = photosTagService.get(albumId);
            // 时间线和热门不用添加关系维护
            if (PhotosTag.ALBUM_HOT.equals(photosTag.getName()) || PhotosTag.ALBUM_TIME_LINE.equals(photosTag.getName())) {
                hasAlbum = false;
            } else {
                hasAlbum = true;
            }
        }

        MemberGroup member = RealmUtils.getCurrentUser();
        for (int i = 0; i < urlArray.length; i++) {
            String url = urlArray[i];
            String imgId = imgIdArray[i];

            PhotosImgInfo photosImgInfo = new PhotosImgInfo();
            photosImgInfo.setUrl(url);
            photosImgInfo.setPhotosId(projectId);

            // 先查看该图片链接是否已经存在, 如果存在就不用添加了
            List<PhotosImgInfo> list = photosImgInfoService.list(photosImgInfo);
            if (CollectionUtils.isEmpty(list)) {
                ImgResource imgResource = imgResourceService.get(imgId);
                if (null != imgResource) {
                    photosImgInfo.setTakeTime(imgResource.getShootTime());
                }

                photosImgInfo.setOperateNum(0);
                photosImgInfo.setViewNum(0);
                photosImgInfo.setCreateBy(member.getId());
                photosImgInfo.setUpdateBy(member.getId());
                photosImgInfo.setImgResourceId(imgId);
                photosImgInfo.setCanDel(PhotosImgInfo.CAN_NOT_DEL);
                photosImgInfoService.insert(photosImgInfo);
            } else {
                photosImgInfo = list.get(0);
            }

            // 有分类id就添加对应关系
            if (hasAlbum) {
                PhotosImgTag photoImgTag = new PhotosImgTag();
                photoImgTag.setImgId(photosImgInfo.getId());
                photoImgTag.setTagId(albumId);

                // 先查看图片与相册的关系是否已经存在, 有就不用添加了
                List<PhotosImgTag> relationList = photoAlbumPicService.list(photoImgTag);
                if (CollectionUtils.isEmpty(relationList)) {
                    photoImgTag.setPhotosId(projectId);
                    photoAlbumPicService.insert(photoImgTag);
                }
            }
        }
        try {
            photosCountBizService.CountImgNum(projectId, new String[] {albumId});
        } catch (Exception e) {
            logger.error("添加照片添加各照片数量冗余数异常", e);
        }
        try {
            PhotoProject photoProject = photoProjectService.get(projectId);
            CMomentSave cMomentSave = new CMomentSave();
            Map<String, Object> mmp = Maps.newHashMap();
            String[] picArr = urlArray;
            if(urlArray.length>9){
                picArr = Arrays.copyOf(urlArray, 9);
            }
            mmp.put("photoProjectId",projectId);
            mmp.put("pics",String.join("|", picArr));
            mmp.put("createBy",photoProject.getMemberId());
            mmp.put("photoTitle",photoProject.getName());
            cMomentSave.setDatas(mmp);
            cMomentSave.setPartnerId(photoProject.getMemberId());
            cMomentSave.setBizId(projectId);
            cMomentSave.setMomentType(MomentType.PHOTO_PUBLISH.getCode());
            momentBizService.businessSaveCMoment(cMomentSave);
        }catch (Exception e){
            logger.error("上传相册同时发布动态--失败");
        }
    }

    /**
     * 获取所有分类
     * @param photosId
     * @return
     */
    public List<PhotosTag> tags(String photosId) {
        if (StringUtils.isEmpty(photosId)) {
            throw new BusinessException("相册id不能为空");
        }

        PhotosTag param = new PhotosTag();
        param.setPhotosId(photosId);
        List<PhotosTag> tags = photosTagService.list(param);

        Iterator<PhotosTag> iterator = tags.iterator();
        while (iterator.hasNext()) {
            PhotosTag tagOutput = iterator.next();
            if (PhotosTag.ALBUM_HOT.equals(tagOutput.getName()) || PhotosTag.ALBUM_CHOICENESS.equals(tagOutput.getName())) {
                iterator.remove();
            }
        }

        return tags;
    }
}
